const express = require('express');
const cors = require('cors');
const path = require('path');
const morgan = require('morgan');

// 导入数据库连接
const { connectDB } = require('./database/db');

// 导入中间件
const { 
  notFound, 
  errorHandler, 
  requestLogger 
} = require('./middleware');

// 导入路由
const authRoutes = require('./routes/auth');
const orderRoutes = require('./routes/orders');
const userRoutes = require('./routes/users');
const statisticsRoutes = require('./routes/statistics');

const app = express();

// 连接数据库
connectDB();

// 信任代理（如果部署在代理后面）
app.set('trust proxy', 1);

// CORS配置
const corsOptions = {
  origin: function (origin, callback) {
    // 允许的源列表
    const allowedOrigins = [
      'http://localhost:3000',
      'http://localhost:3000/',
      'http://localhost:3001',
      'http://localhost:3001/',
      'http://localhost:8080',
      'http://localhost:8080/',
      'http://127.0.0.1:3000',
      'http://127.0.0.1:3000/',
      'http://127.0.0.1:3001',
      'http://127.0.0.1:3001/',
      'http://127.0.0.1:8080',
      'http://127.0.0.1:8080/'
    ];
    
    // 如果没有origin（比如移动应用），也允许
    if (!origin) return callback(null, true);
    
    if (allowedOrigins.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      // 在开发环境中允许所有源（修复环境变量检查）
      const isDev = !process.env.NODE_ENV || process.env.NODE_ENV === 'development';
      if (isDev) {
        console.log(`CORS: 允许来源 ${origin} (开发模式)`);
        callback(null, true);
      } else {
        console.error(`CORS: 拒绝来源 ${origin}`);
        callback(new Error('CORS策略不允许此源访问'));
      }
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept'],
  optionsSuccessStatus: 200 // 支持老版本浏览器
};

// 基础中间件
app.use(cors(corsOptions));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 日志中间件
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
  app.use(requestLogger);
} else {
  app.use(morgan('combined'));
}

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use(express.static(path.join(__dirname, 'public')));

// 管理后台路由
app.get('/admin', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'admin.html'));
});

// 健康检查端点
app.get('/health', (req, res) => {
  res.status(200).json({
    success: true,
    message: 'HarmonyOS工单管理系统后端服务运行正常',
    code: 200,
    data: {
      timestamp: new Date().toISOString(),
      environment: process.env.NODE_ENV || 'development',
      version: '1.0.0'
    }
  });
});

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/users', userRoutes);
app.use('/api/statistics', statisticsRoutes);

// API根路径
app.get('/api', (req, res) => {
  res.status(200).json({
    success: true,
    message: 'HarmonyOS工单管理系统 API v1.0',
    code: 200,
    data: {
      version: '1.0.0',
      endpoints: {
        auth: '/api/auth',
        orders: '/api/orders',
        users: '/api/users',
        statistics: '/api/statistics'
      },
      timestamp: new Date().toISOString()
    }
  });
});

// 404处理
app.use(notFound);

// 全局错误处理
app.use(errorHandler);

module.exports = app;
